package com.apartment.own.service.impl;

import com.apartment.common.utils.DateUtils;
import com.apartment.own.domain.OwnAccountDetails;
import com.apartment.own.domain.OwnCategoryEntity;
import com.apartment.own.mapper.OwnAccountDetailsMapper;
import com.apartment.own.mapper.OwnCategoryEntityMapper;
import com.apartment.own.service.IOwnAccountDetailsService;
import com.apartment.own.service.IOwnCategoryEntityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 账单详情Service业务层处理
 *
 * @author @Dog_E
 * @date 2020-08-28
 */
@Service
public class OwnCategoryEntityImpl extends ServiceImpl<OwnCategoryEntityMapper, OwnCategoryEntity> implements IOwnCategoryEntityService {
    /**
     * 添加物品
     */
    @Autowired
    private OwnCategoryEntityMapper entityMapper;

    @Override
    public int insertItems(OwnCategoryEntity categoryEntity) {
        save(categoryEntity);
        return 1;
    }

    /**
     * 查询物品
     */
    @Override
    public List<OwnCategoryEntity> listWithTree() {
        List<OwnCategoryEntity> entities = baseMapper.selectList(null);
        //2. 组装成父子的树形结构
        //2.1 找到所有一级分类
        List<OwnCategoryEntity> level1Menus = entities.stream().filter(categoryEntity -> {
            //查出一级分类后返回
            return categoryEntity.getParentCid() == 0;
        }).map((menu) -> {
            //查出当前分类 的所有下级分类,set进去后返回
            menu.setChildren(getChildren(menu, entities));
            return menu;
        }).collect(Collectors.toList());
        return level1Menus;
    }

    private List<OwnCategoryEntity> getChildren(OwnCategoryEntity categoryEntity, List<OwnCategoryEntity> all) {

        List<OwnCategoryEntity> entityList = all.stream().filter(category -> {
            return category.getParentCid().equals(categoryEntity.getCatId());
        }).map(menu -> {
            menu.setChildren(getChildren(menu, all));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return entityList;
    }
}
